package services;

import java.io.IOException;
import java.io.PrintWriter;
import java.sql.SQLException;
import java.util.ArrayList;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.w3c.dom.Document;
import org.w3c.dom.Element;

import DataAccess.CayThaoLuanDA;
import DataAccess.LogThaoTacDA;
import DataAccess.NguoiDungDA;
import DataAccess.NhomDA;
import DataAccess.NodeThaoLuanDA;

import pojo.CayThaoLuanPOJO;
import pojo.LogThaoTacPOJO;
import pojo.LogUtil;
import pojo.NguoiDungPOJO;
import pojo.NhomPOJO;
import pojo.NodeThaoLuanPOJO;
import pojo.PairValue;
import util.ClientSender;
import util.Common;
import util.XMLBuidler;

/**
 * Servlet implementation class CayThaoLuanServlet
 */
@WebServlet("/CayThaoLuanServlet")
public class CayThaoLuanServlet extends BaseServlet {
	private static final long serialVersionUID = 1L;

	/**
	 * @see HttpServlet#HttpServlet()
	 */
	public CayThaoLuanServlet() {
		super();
		// TODO Auto-generated constructor stub
	}

	/**
	 * @throws IOException
	 * @throws ServletException
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {

		PrintWriter out = response.getWriter();
		try {
			String cmd = getParameter(request, Protocol.CMD);
			System.out.println(cmd);
			CayThaoLuanDA cda = new CayThaoLuanDA();
			if (cmd.equals(Protocol.TAO_CAY)) {
				String nguoiTao = getParameter(request, Protocol.NGUOI_DUNG);
				String noiDung = getParameter(request, Protocol.NOI_DUNG);
				int idNhom = Integer.parseInt(getParameter(request, Protocol.ID_NHOM));

				CayThaoLuanPOJO cay = new CayThaoLuanPOJO();
				cay.setNguoiTao(nguoiTao);
				cay.setIdNhom(idNhom);
				cay.setNoiDung(noiDung);

				int idCay = -1;

				idCay = cda.insert(cay);

				cay.setId(idCay);
				out.print(idCay);

				// Gui cho may thang trong nhom
				ArrayList<PairValue> params = new ArrayList<PairValue>();
				params.add(new PairValue(Protocol.CMD, Protocol.TAO_CAY));
				params.add(new PairValue(Protocol.ID_CAY, idCay + ""));
				params.add(new PairValue(Protocol.NGUOI_GUI, nguoiTao));
				params.add(new PairValue(Protocol.ID_NHOM, idNhom + ""));

				ClientSender.sendToGroup(idNhom, params);
				System.out.println(cmd+" n.tao="+nguoiTao);
				
				//Ghi log
				new LogThaoTacDA().insert(nguoiTao, idCay+"",idCay,LogUtil.TAO_CAY);
				

			} else if (cmd.equals(Protocol.LAY_DANH_SACH_CAY)) {
				String nguoiDung = getParameter(request, Protocol.NGUOI_DUNG);

				ArrayList<NhomPOJO> lstNhom = new NhomDA().getNhomNguoiDung(nguoiDung);

				Document doc = XMLBuidler.BuildXML("Root");
				if (lstNhom != null) {
					for (NhomPOJO nhom : lstNhom) {
						Element element = nhom.createContactXMLElement(doc);
						ArrayList<CayThaoLuanPOJO> lstCay = new CayThaoLuanDA().getByNhom(nhom.getId());
						for (CayThaoLuanPOJO cay : lstCay) {
							element.appendChild(cay.createXMLElement(doc));
						}
						doc.getFirstChild().appendChild(element);
					}
				}

				out.print(XMLBuidler.docToString(doc));

			} else if (cmd.equals(Protocol.LAY_CAY)) {
				String idCay = getParameter(request, Protocol.ID);

				CayThaoLuanPOJO cay = cda.get(Integer.parseInt(idCay));
				if (cay != null) {					
					out.print(XMLBuidler.taoCay(cay));
				} else {
					out.print(Protocol.SERVER_ERROR);
				}
			} else if (cmd.equals(Protocol.THEM_NODE)) {

				String idNodeCha, idCay, nguoiTao, noiDung, ghiChu;
				idNodeCha = getParameter(request, Protocol.ID);
				idCay = getParameter(request, Protocol.ID_CAY);
				nguoiTao = getParameter(request, Protocol.NGUOI_DUNG);
				noiDung = getParameter(request, Protocol.NOI_DUNG);

				ghiChu = getParameter(request, Protocol.GHI_CHU, "");

				NodeThaoLuanPOJO node = new NodeThaoLuanPOJO();
				node.setIdNodeCha(Integer.parseInt(idNodeCha));
				node.setIdCay(Integer.parseInt(idCay));
				node.setNguoiTao(nguoiTao);
				node.setNoiDung(noiDung);
				node.setGhiChu(ghiChu);

				NodeThaoLuanDA nda = new NodeThaoLuanDA();
				nda.insertNode(node);
				
				String rs = XMLBuidler.nodeToXMLString(node);
				out.print(rs);
				System.out.println(rs);
				// Gửi thông tin cho các thành viên trong nhóm
				ArrayList<NguoiDungPOJO> lstNguoiDung = new NguoiDungDA().getNguoiDungCuaCay(Integer.parseInt(idCay));

				ArrayList<PairValue> params = new ArrayList<PairValue>();
				params.add(new PairValue(Protocol.CMD, Protocol.THEM_NODE));
				params.add(new PairValue(Protocol.NOI_DUNG, rs));
				ArrayList<String> lstRegId = Common.retrieveRegId(lstNguoiDung);
				ClientSender.send(lstRegId, params, 30);
				
				//Ghi log
				new LogThaoTacDA().insert(nguoiTao, node.getId()+"",Integer.parseInt(idCay),LogUtil.THEM_NODE);

			} else if (cmd.equals(Protocol.XOA_NODE)) {
				int idNode = Integer.parseInt(getParameter(request, Protocol.ID));
				int idCay = Integer.parseInt(getParameter(request, Protocol.ID_CAY));
				long rs = new NodeThaoLuanDA().deleteNode(idCay, idNode);
				String nguoiDung=getParameter(request, Protocol.NGUOI_DUNG);
				out.print(rs);
				NodeThaoLuanPOJO node = new NodeThaoLuanDA().get(idNode);
				String noiDung = XMLBuidler.nodeToXMLString(node);		
				
				// Gửi thông tin cho các thành viên trong nhóm
				ArrayList<NguoiDungPOJO> lstNguoiDung = new NguoiDungDA().getNguoiDungCuaCay(idCay);
				ArrayList<PairValue> params = new ArrayList<PairValue>();
				params.add(new PairValue(Protocol.CMD, Protocol.XOA_NODE));
				params.add(new PairValue(Protocol.NOI_DUNG, noiDung));

				ArrayList<String> lstRegId = Common.retrieveRegId(lstNguoiDung);
				ClientSender.send(lstRegId, params, 30);
				
				//Ghi log
				new LogThaoTacDA().insert(nguoiDung,idNode+"",idCay,LogUtil.XOA_NODE);

			} else if (cmd.equals(Protocol.CAP_NHAT_NODE)) {
				int idNode = Integer.parseInt(getParameter(request, Protocol.ID));
				int idCay = Integer.parseInt(getParameter(request, Protocol.ID_CAY));
				String noiDung = getParameter(request, Protocol.NOI_DUNG);
				String ghiChu = getParameter(request, Protocol.GHI_CHU, "");
				String nguoiDung=getParameter(request, Protocol.NGUOI_DUNG);
				NodeThaoLuanPOJO node = new NodeThaoLuanPOJO();
				node.setId(idNode);
				node.setIdCay(idCay);
				node.setGhiChu(ghiChu);
				node.setNoiDung(noiDung);
				System.out.println(idNode+" "+idCay+" "+noiDung+" "+ghiChu+" "+nguoiDung);
				long rs = new NodeThaoLuanDA().update(node);
				out.print(rs);

				NodeThaoLuanPOJO node2 = new NodeThaoLuanDA().get(idNode);
				String xml = XMLBuidler.nodeToXMLString(node2);
				
				// Gửi thông tin cho các thành viên trong nhóm
				ArrayList<NguoiDungPOJO> lstNguoiDung = new NguoiDungDA().getNguoiDungCuaCay(idCay);
				ArrayList<PairValue> params = new ArrayList<PairValue>();
				params.add(new PairValue(Protocol.CMD, Protocol.CAP_NHAT_NODE));
				params.add(new PairValue(Protocol.NOI_DUNG, xml));

				ArrayList<String> lstRegId = Common.retrieveRegId(lstNguoiDung);
				ClientSender.send(lstRegId, params, 30);
				
				//Ghi log
				new LogThaoTacDA().insert(nguoiDung,idNode+"",idCay,LogUtil.CAP_NHAT_NODE);

			}else if(cmd.equals(Protocol.THONG_TIN)){
				int idCay=Integer.parseInt(getParameter(request, Protocol.ID_CAY));
				CayThaoLuanPOJO cay=new CayThaoLuanDA().get(idCay);
				out.print(cay.toXMLString());
			}else if(cmd.equals(Protocol.MOI_VAO_THAO_LUAN)){
				String nguoiGui = getParameter(request, Protocol.NGUOI_GUI);
				String nguoiNhan = getParameter(request, Protocol.NGUOI_NHAN);
				String idCay=getParameter(request, Protocol.ID_CAY);
				String idNhom = getParameter(request, Protocol.ID_NHOM);
				ArrayList<PairValue> params = new ArrayList<PairValue>();
				params.add(new PairValue(Protocol.CMD, Protocol.TAO_CAY));
				params.add(new PairValue(Protocol.ID_CAY, idCay ));
				params.add(new PairValue(Protocol.NGUOI_GUI, nguoiGui));
				params.add(new PairValue(Protocol.ID_NHOM, idNhom ));

				String regID=new NguoiDungDA().get(nguoiNhan).getDeviceID();
				ClientSender.send(regID, params);
			}

		} catch (Exception e) {
			out.print(Protocol.SERVER_ERROR);			
			e.printStackTrace(System.out);
			if(Protocol.DEBUG==1){
				e.printStackTrace(out);
			}
		}
		out.close();
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException,
			ServletException {
		doGet(request, response);
	}

}
